# -*- coding:utf-8 -*-

import os
import time
import yaml
from utils import root_dir
from utils.log_utils import log_debug

"""
IO工具
"""


def convert_abspath(related_path):
    """
    加上根路径，得到绝对路径
    :param related_path:
    :return:
    """
    return root_dir + '/' + related_path


def conveter_model_path(config):
    """
    根据net.module和时间生成保存model的path
    :return:
    """
    model_name = '/'.join(config.net.module.split('.')[-3:-1])
    log_dir = config.log.board_dir if config.log and config.log.board_dir else 'data/board/{}/'.format(model_name)
    log_dir = convert_abspath(log_dir + '{}'.format(time.strftime("%m%d%H%M", time.localtime())))
    log_debug('save tensorboard to', fore='dy')
    log_debug(log_dir, back='g')

    model_dir = config.save.model_dir if config.save.model_dir else 'data/model/{}/'.format(model_name)
    model_dir = convert_abspath(model_dir + '{}/'.format(time.strftime("%m%d%H%M", time.localtime())))
    if config.save.is_save:
        log_debug('save model to', fore='dy')
        log_debug(log_dir, back='g')
    if not os.path.exists(model_dir):
        os.makedirs(model_dir)
    model_path = model_dir + 'model'
    return log_dir, model_path


def get_yml(yml_path):
    """
    获得yml文件
    :param yml_path:
    :return:
    """
    config = yaml.safe_load(open(yml_path, encoding='utf-8'))
    return config


def module_to_path(module_str):
    """
    module类型字符串转path类型
    :param module_str:
    :return:
    """
    path = '/'.join(module_str.split('.'))
    return path


def path_to_module(path_str):
    """
    path类型字符串转module类型
    :param path_str:
    :return:
    """
    path = '.'.join(path_str.split('/'))
    return path
